"use client"

import { useState, useEffect, useMemo } from "react"
import { Outlet, useNavigate, useLocation } from "react-router-dom"
import {
  Layout,
  Menu,
  Button,
  Input,
  Avatar,
  Dropdown,
  Badge,
  Tooltip,
  Card,
  List,
  Tag,
  Typography,
  Empty,
  Drawer,
} from "antd"
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  BellOutlined,
  UserOutlined,
  SearchOutlined,
  DashboardOutlined,
  ProjectOutlined,
  SettingOutlined,
  TeamOutlined,
  CloudServerOutlined,
  CloseOutlined,
  MenuOutlined,
} from "@ant-design/icons"
import { useHosts } from "../contexts/HostsContext"
import "../styles/global.scss"
import "./MainLayout.scss"

const { Header, Sider, Content, Footer } = Layout
const { Text, Title } = Typography

const MainLayout = () => {
  const [collapsed, setCollapsed] = useState(false)
  const [mobileMenuVisible, setMobileMenuVisible] = useState(false)
  const navigate = useNavigate()
  const location = useLocation()
  const { setFilter, departments, projects, modules, hosts, hostsBlocks } = useHosts()
  const [selectedKeys, setSelectedKeys] = useState<string[]>([])
  const [openKeys, setOpenKeys] = useState<string[]>([])
  const [searchText, setSearchText] = useState("")
  const [showSearchResults, setShowSearchResults] = useState(false)
  const [isMobile, setIsMobile] = useState(false)

  // Check if the screen is mobile
  useEffect(() => {
    const checkIsMobile = () => {
      setIsMobile(window.innerWidth < 768)
      if (window.innerWidth < 768) {
        setCollapsed(true)
      }
    }

    checkIsMobile()
    window.addEventListener("resize", checkIsMobile)

    return () => {
      window.removeEventListener("resize", checkIsMobile)
    }
  }, [])

  useEffect(() => {
    // Set selected keys based on current path
    const pathSnippets = location.pathname.split("/").filter((i) => i)
    if (pathSnippets.length === 0) {
      setSelectedKeys(["dashboard"])
    } else if (pathSnippets[0] === "projects" && pathSnippets.length === 1) {
      setSelectedKeys(["projects"])
    } else if (pathSnippets[0] === "departments") {
      setSelectedKeys([`department-${pathSnippets[1]}`])
      setOpenKeys((prev) => [...new Set([...prev, "departments"])])
    } else if (pathSnippets[0] === "settings") {
      setSelectedKeys(["settings"])
    }
  }, [location.pathname])

  // Helper function to highlight matching text
  const highlightText = (text: string, query: string) => {
    if (!query) return text

    const parts = text.split(new RegExp(`(${query})`, "gi"))
    return (
      <>
        {parts.map((part, i) =>
          part.toLowerCase() === query.toLowerCase() ? (
            <span key={i} style={{ backgroundColor: "#ffd666", padding: "0 2px" }}>
              {part}
            </span>
          ) : (
            part
          ),
        )}
      </>
    )
  }

  // Generate a consistent color based on department
  const getDepartmentColor = (departmentId: string) => {
    const department = departments.find((d) => d.id === departmentId)
    return department?.color || "#3b82f6"
  }

  // Search functionality that includes projects, modules, and hosts
  const searchResults = useMemo(() => {
    if (!searchText) return []

    const results = []

    // Search in projects
    const matchedProjects = projects.filter(
      (project) =>
        project.name.toLowerCase().includes(searchText.toLowerCase()) ||
        (project.description && project.description.toLowerCase().includes(searchText.toLowerCase())),
    )

    for (const project of matchedProjects) {
      const department = departments.find((d) => d.id === project.departmentId)
      results.push({
        type: "project",
        id: project.id,
        name: project.name,
        department: department?.name || "",
        departmentId: project.departmentId,
        highlight: highlightText(project.name, searchText),
        description: project.description || "",
      })
    }

    // Search in modules
    const matchedModules = modules.filter(
      (module) =>
        module.name.toLowerCase().includes(searchText.toLowerCase()) ||
        (module.description && module.description.toLowerCase().includes(searchText.toLowerCase())),
    )

    for (const module of matchedModules) {
      const project = projects.find((p) => p.id === module.projectId)
      if (project) {
        const department = departments.find((d) => d.id === project.departmentId)
        results.push({
          type: "module",
          id: module.id,
          projectId: module.projectId,
          name: module.name,
          projectName: project.name,
          department: department?.name || "",
          departmentId: project.departmentId,
          highlight: highlightText(module.name, searchText),
          description: module.description || "",
        })
      }
    }

    // Search in hosts blocks
    const matchedHostsBlocks = hostsBlocks.filter(
      (block) =>
        block.name.toLowerCase().includes(searchText.toLowerCase()) ||
        (block.description && block.description.toLowerCase().includes(searchText.toLowerCase())) ||
        block.content.toLowerCase().includes(searchText.toLowerCase()),
    )

    for (const block of matchedHostsBlocks) {
      const project = projects.find((p) => p.id === block.projectId)
      if (project) {
        const department = departments.find((d) => d.id === project.departmentId)
        const module = block.moduleId ? modules.find((m) => m.id === block.moduleId) : null
        results.push({
          type: "hostsBlock",
          id: block.id,
          projectId: block.projectId,
          moduleId: block.moduleId,
          name: block.name,
          projectName: project.name,
          moduleName: module?.name,
          department: department?.name || "",
          departmentId: project.departmentId,
          highlight: highlightText(block.name, searchText),
          description: block.description || "",
        })
      }
    }

    return results
  }, [searchText, projects, modules, hostsBlocks, departments])

  const handleSearch = (value: string) => {
    setSearchText(value)
    setFilter((prev) => ({ ...prev, search: value }))
    setShowSearchResults(value.length > 0)
  }

  const handleCloseSearch = () => {
    setSearchText("")
    setShowSearchResults(false)
  }

  const userMenu = (
    <Menu
      items={[
        {
          key: "1",
          label: "个人设置",
        },
        {
          key: "2",
          label: "退出登录",
        },
      ]}
    />
  )

  const notificationMenu = (
    <Menu
      items={[
        {
          key: "1",
          label: "暂无通知",
        },
      ]}
    />
  )

  const handleOpenChange = (keys: string[]) => {
    setOpenKeys(keys)
  }

  const toggleMobileMenu = () => {
    setMobileMenuVisible(!mobileMenuVisible)
  }

  const renderSidebar = () => {
    return (
      <Menu
        theme="dark"
        mode="inline"
        selectedKeys={selectedKeys}
        openKeys={collapsed ? [] : openKeys}
        onOpenChange={handleOpenChange}
        onClick={({ key }) => {
          if (key === "dashboard") {
            navigate("/")
          } else if (key === "projects") {
            navigate("/projects")
          } else if (key === "settings") {
            navigate("/settings")
          } else if (key.startsWith("department-")) {
            const departmentId = key.replace("department-", "")
            navigate(`/departments/${departmentId}`)
          }
          if (isMobile) {
            setMobileMenuVisible(false)
          }
        }}
        style={{ background: "#1e293b", borderRight: "none" }}
        items={[
          {
            key: "dashboard",
            icon: <DashboardOutlined />,
            label: "仪表盘",
          },
          {
            key: "projects",
            icon: <ProjectOutlined />,
            label: "项目管理",
          },
          {
            key: "departments",
            icon: <TeamOutlined />,
            label: "部门视图",
            children: departments.map((dept) => ({
              key: `department-${dept.id}`,
              label: dept.name,
            })),
          },
          {
            key: "settings",
            icon: <SettingOutlined />,
            label: "系统设置",
          },
        ]}
      />
    )
  }

  return (
    <Layout className="main-layout">
      {/* Desktop Sidebar */}
      {!isMobile && (
        <Sider
          trigger={null}
          collapsible
          collapsed={collapsed}
          width={220}
          className="sidebar"
          style={{
            boxShadow: "0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",
            background: "#1e293b",
            position: "fixed",
            height: "100vh",
            zIndex: 1000,
          }}
        >
          <div
            className="logo"
            style={{
              height: "64px",
              display: "flex",
              alignItems: "center",
              padding: "0 24px",
              color: "white",
              fontSize: "18px",
              fontWeight: "600",
              background: "#0f172a",
            }}
          >
            <CloudServerOutlined className="logo-icon" style={{ fontSize: "24px", marginRight: "12px" }} />
            {!collapsed && <span className="logo-text">Hosts管理</span>}
          </div>
          {renderSidebar()}
        </Sider>
      )}

      {/* Mobile Sidebar Drawer */}
      <Drawer
        placement="left"
        closable={false}
        onClose={() => setMobileMenuVisible(false)}
        open={isMobile && mobileMenuVisible}
        width={250}
        bodyStyle={{ padding: 0, background: "#1e293b" }}
      >
        <div
          style={{
            height: "64px",
            display: "flex",
            alignItems: "center",
            padding: "0 24px",
            color: "white",
            fontSize: "18px",
            fontWeight: "600",
            background: "#0f172a",
          }}
        >
          <CloudServerOutlined style={{ fontSize: "24px", marginRight: "12px" }} />
          <span>Hosts Manager</span>
        </div>
        {renderSidebar()}
      </Drawer>

      <Layout
        className="site-layout"
        style={{
          marginLeft: isMobile ? 0 : collapsed ? "80px" : "220px",
          transition: "margin-left 0.2s",
        }}
      >
        <Header
          className="site-header"
          style={{
            padding: "0",
            background: "white",
            height: "64px",
            boxShadow: "0 1px 3px rgba(0, 0, 0, 0.05)",
            position: "sticky",
            top: "0",
            zIndex: "900",
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
          }}
        >
          <div
            className="header-left"
            style={{
              paddingLeft: "16px",
              display: "flex",
              alignItems: "center",
            }}
          >
            {isMobile ? (
              <Button
                type="text"
                icon={<MenuOutlined />}
                onClick={toggleMobileMenu}
                style={{ fontSize: "16px", width: "40px", height: "40px" }}
              />
            ) : (
              <Button
                type="text"
                icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
                onClick={() => setCollapsed(!collapsed)}
                style={{ fontSize: "16px", width: "40px", height: "40px" }}
              />
            )}
          </div>
          <div
            className="header-right"
            style={{
              display: "flex",
              alignItems: "center",
              gap: isMobile ? "8px" : "16px",
              paddingRight: "16px",
              position: "relative",
            }}
          >
            <div style={{ position: "relative" }}>
              <Input
                placeholder="全局搜索..."
                prefix={<SearchOutlined style={{ color: "#94a3b8" }} />}
                suffix={
                  searchText ? (
                    <CloseOutlined style={{ color: "#94a3b8", cursor: "pointer" }} onClick={handleCloseSearch} />
                  ) : null
                }
                value={searchText}
                onChange={(e) => handleSearch(e.target.value)}
                style={{
                  width: isMobile ? "180px" : "280px",
                  borderRadius: "8px",
                }}
                size="middle"
              />

              {/* Search Results Dropdown */}
              {showSearchResults && (
                <Card
                  style={{
                    position: "absolute",
                    top: "40px",
                    left: 0,
                    width: isMobile ? "280px" : "400px",
                    maxHeight: "500px",
                    overflowY: "auto",
                    zIndex: 1000,
                    boxShadow: "0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)",
                    borderRadius: "8px",
                  }}
                  bodyStyle={{ padding: "12px" }}
                >
                  {searchResults.length > 0 ? (
                    <>
                      <div style={{ marginBottom: "12px" }}>
                        <Title level={5} style={{ margin: 0 }}>
                          搜索结果
                        </Title>
                        <Text type="secondary" style={{ fontSize: "12px" }}>
                          找到 {searchResults.length} 个结果
                        </Text>
                      </div>
                      <List
                        itemLayout="horizontal"
                        dataSource={searchResults}
                        renderItem={(item) => (
                          <List.Item
                            style={{
                              padding: "8px 12px",
                              borderRadius: "6px",
                              cursor: "pointer",
                              transition: "background-color 0.2s",
                              marginBottom: "4px",
                              border: "1px solid #f1f5f9",
                            }}
                            onClick={() => {
                              if (item.type === "project") {
                                navigate(`/projects/${item.id}`)
                              } else if (item.type === "module") {
                                navigate(`/projects/${item.projectId}/modules/${item.id}`)
                              } else if (item.type === "hostsBlock") {
                                if (item.moduleId) {
                                  navigate(`/projects/${item.projectId}/modules/${item.moduleId}`)
                                } else {
                                  navigate(`/projects/${item.projectId}`)
                                }
                              }
                              setShowSearchResults(false)
                              setSearchText("")
                            }}
                          >
                            <List.Item.Meta
                              avatar={
                                <div
                                  style={{
                                    width: "36px",
                                    height: "36px",
                                    borderRadius: "50%",
                                    background: `linear-gradient(135deg, ${getDepartmentColor(
                                      item.departmentId,
                                    )} 0%, ${getDepartmentColor(item.departmentId)}80 100%)`,
                                    display: "flex",
                                    alignItems: "center",
                                    justifyContent: "center",
                                    color: "white",
                                    fontSize: "14px",
                                    fontWeight: "bold",
                                  }}
                                >
                                  {item.type === "project" ? "P" : item.type === "module" ? "M" : "H"}
                                </div>
                              }
                              title={
                                <div style={{ display: "flex", alignItems: "center", flexWrap: "wrap", gap: "4px" }}>
                                  {item.type === "module" && (
                                    <>
                                      <Text style={{ fontSize: "13px", color: "#64748b" }}>{item.projectName}</Text>
                                      <Text style={{ fontSize: "13px", color: "#64748b" }}>&gt;</Text>
                                      <Text strong style={{ fontSize: "13px" }}>
                                        {item.highlight}
                                      </Text>
                                    </>
                                  )}
                                  {item.type === "hostsBlock" && (
                                    <>
                                      <Text style={{ fontSize: "13px", color: "#64748b" }}>
                                        {item.projectName} {item.moduleName ? `> ${item.moduleName}` : ""} &gt;
                                      </Text>
                                      <Text strong style={{ fontSize: "13px" }}>
                                        {item.highlight}
                                      </Text>
                                    </>
                                  )}
                                  {item.type === "project" && (
                                    <Text strong style={{ fontSize: "13px" }}>
                                      {item.highlight}
                                    </Text>
                                  )}
                                  <Tag
                                    style={{
                                      background: `${getDepartmentColor(item.departmentId)}20`,
                                      color: getDepartmentColor(item.departmentId),
                                      borderRadius: "12px",
                                      border: "none",
                                      fontSize: "11px",
                                      padding: "0 8px",
                                    }}
                                  >
                                    {item.department}
                                  </Tag>
                                </div>
                              }
                              description={
                                <Text type="secondary" style={{ fontSize: "12px" }}>
                                  {item.description ? (
                                    item.description.length > 60 ? (
                                      `${item.description.substring(0, 60)}...`
                                    ) : (
                                      item.description
                                    )
                                  ) : (
                                    <span
                                      style={{
                                        fontStyle: "italic",
                                        color: "#94a3b8",
                                      }}
                                    >
                                      无描述
                                    </span>
                                  )}
                                </Text>
                              }
                            />
                          </List.Item>
                        )}
                      />
                    </>
                  ) : (
                    <Empty
                      description={`没有找到与 "${searchText}" 相关的内容`}
                      image={Empty.PRESENTED_IMAGE_SIMPLE}
                      style={{ margin: "24px 0" }}
                    />
                  )}
                </Card>
              )}
            </div>
            {!isMobile && (
              <Tooltip title="通知">
                <Dropdown overlay={notificationMenu} trigger={["click"]}>
                  <Badge count={0} size="small">
                    <Button
                      type="text"
                      icon={<BellOutlined />}
                      style={{
                        color: "#64748b",
                        width: "40px",
                        height: "40px",
                      }}
                    />
                  </Badge>
                </Dropdown>
              </Tooltip>
            )}
            <Dropdown overlay={userMenu} trigger={["click"]}>
              <div
                style={{
                  display: "flex",
                  alignItems: "center",
                  gap: "8px",
                  cursor: "pointer",
                  padding: "4px 8px",
                  borderRadius: "8px",
                  transition: "all 0.2s",
                }}
              >
                <Avatar
                  size="small"
                  icon={<UserOutlined />}
                  style={{
                    backgroundColor: "#3b82f6",
                    color: "white",
                  }}
                />
                {!isMobile && (
                  <span
                    style={{
                      fontSize: "14px",
                      color: "#1e293b",
                      fontWeight: "500",
                    }}
                  >
                    管理员
                  </span>
                )}
              </div>
            </Dropdown>
          </div>
        </Header>
        <Content
          style={{
            padding: isMobile ? "16px" : "24px",
            minHeight: "calc(100vh - 64px - 40px)",
            background: "#f9fafb",
          }}
        >
          <div style={{ maxWidth: "1280px", margin: "0 auto" }}>
            <Outlet />
          </div>
        </Content>
        <Footer
          style={{
            textAlign: "center",
            padding: "12px 0",
            fontSize: "12px",
            color: "#64748b",
            height: "40px",
            borderTop: "1px solid #e5e7eb",
            background: "white",
          }}
        >
          Hosts Manager ©{new Date().getFullYear()} 企业内部系统
        </Footer>
      </Layout>
    </Layout>
  )
}

export default MainLayout
